package com.shushan.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.fingerprintidentify.FingerprintIdentify;
import com.android.fingerprintidentify.base.BaseFingerprint;
import com.shushan.login.LoginOrRegisterActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.android.net.bean.NetRetBean;
import com.android.net.util.NetToastUtil;
import com.shushan.ui.PopupDialog;
import com.shushan.ui.VerificationCodeView;
import com.shushan.ui.WaitDialog;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.ToastUtils;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;


/**
 * @ClassName: BaseFragment
 * @Desciption: 所有的Fragment的基类
 * @author: yichaohua
 * @date: 2018-01-05
 */
public class BaseFragment extends Fragment {

    private static final String TAG = "BaseFragment";

    private WaitDialog mWaitDialog;
    private Dialog singleLoginDialog;
    private FingerprintIdentify mFingerprintIdentify;
    private BaseActivity baseActivity;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        baseActivity = (BaseActivity)getActivity();
        mWaitDialog = new WaitDialog(getActivity(), R.style.Dialog_Translucent_Background);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if(mWaitDialog != null  && !getActivity().isFinishing()){
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }

        if(singleLoginDialog != null  && !getActivity().isFinishing()){
            singleLoginDialog.dismiss();
            singleLoginDialog = null;
        }
    }

    protected void startActivity(Class<? extends Activity> cls){
        baseActivity.setAllowBack(true);
        startActivity(new Intent(getActivity(),cls));
    }

    public void startActivityAllow(Intent intent) {
        if(intent == null){
            return;
        }

        baseActivity.setAllowBack(true);
        startActivity(intent);
    }

    protected void startActivityForResult(Class<? extends Activity> cls){
        baseActivity.setAllowBack(true);
        startActivityForResult(new Intent(getActivity(),cls),100);
    }

    /**
     * 跳转Activity
     * skip Another Activity
     *
     * @param cls
     */
    protected void skipAnotherActivity(Class<? extends Activity> cls) {
        Intent intent = new Intent(getActivity(), cls);
        startActivity(intent);
        onBackAction();
    }

    protected void onBackAction(){
        if(mWaitDialog != null){
            mWaitDialog.dismiss();
        }

        if(singleLoginDialog != null){
            singleLoginDialog.dismiss();
        }

        getActivity().finish();
    }

    protected void onBackAction(int resultCode){
        if(mWaitDialog != null){
            mWaitDialog.dismiss();
        }

        if(singleLoginDialog != null){
            singleLoginDialog.dismiss();
        }

        getActivity().setResult(resultCode);
        getActivity().finish();
    }

    protected void showToast( String text){
        ToastUtils.showToast(getActivity(),text);
    }

    protected void showNetError(NetRetBean netRetBean){
        Log.e(TAG,"netRetBean=" + netRetBean.toString());

        if(netRetBean.getServerCode() == 304){
            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
            if(!isChildControl || TextUtils.isEmpty(SharedPreferencesUtils.getStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY))) {
                showHasLoginDialogNoPsw();
            }else{
                showHasLoginDialog();
            }
            return;
        }
        Context context = getActivity();
        if(context != null){
            NetToastUtil.requestError(context, netRetBean);
        }
    }

    protected void showNoMsgError(NetRetBean netRetBean) {
        Log.e(TAG, "netRetBean=" + netRetBean.toString());

        if(netRetBean.getServerCode() == 304){
            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
            if(!isChildControl || TextUtils.isEmpty(SharedPreferencesUtils.getStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY))) {
                showHasLoginDialogNoPsw();
            }else{
                showHasLoginDialog();
            }
            return;
        }
    }

    private void showHasLoginDialogNoPsw() {
        final PushAgent mPushAgent = PushAgent.getInstance(getActivity());
        int currentChildId = BabyApplication.getInstance().getCurrentChildId();
        if(currentChildId > 0){
            mPushAgent.deleteAlias(currentChildId+"", Constants.UMENG_ALIAS_CHILD_ID_KEY, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean isSuccess, String message) {
                    Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                }
            });
        }

        int useId = SharedPreferencesUtils.getIntDate(Constants.CURRENT_USE_ID_SHAREPREFERS_KEY);
        if(useId > 0){
            mPushAgent.deleteAlias(useId+"", Constants.UMENG_ALIAS_USE_ID_KEY, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean isSuccess, String message) {
                    Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                }
            });
        }

        final PopupDialog popupDialog = new PopupDialog(getActivity());
        popupDialog.setMessage("发现您的账号：" + SharedPreferencesUtils.getStringDate(
                Constants.LOGIN_MOBILE_SHAREPREFERS_KEY) + "已经在别的设备上登录，是否重新登录？");
        popupDialog.setPositiveButton("去登录", new PopupDialog.DialogOnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(LoginOrRegisterActivity.class);
                onBackAction();
                SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,false);
            }
        });
        popupDialog.setNegativeButton("取消", new PopupDialog.DialogOnClickListener() {
            @Override
            public void onClick(View v) {
                popupDialog.dismiss();
            }
        });

        if (!getActivity().isFinishing()) {
            popupDialog.show(getActivity().getWindow().getDecorView(),
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        }
    }

    private void showHasLoginDialog(){
        final PushAgent mPushAgent = PushAgent.getInstance(getActivity());
        int currentChildId = BabyApplication.getInstance().getCurrentChildId();
        if(currentChildId > 0){
            mPushAgent.deleteAlias(currentChildId+"", Constants.UMENG_ALIAS_CHILD_ID_KEY, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean isSuccess, String message) {
                    Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                }
            });
        }

        int useId = SharedPreferencesUtils.getIntDate(Constants.CURRENT_USE_ID_SHAREPREFERS_KEY);
        if(useId > 0){
            mPushAgent.deleteAlias(useId+"", Constants.UMENG_ALIAS_USE_ID_KEY, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean isSuccess, String message) {
                    Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                }
            });
        }

        VerificationCodeView codeView = null;
        if(singleLoginDialog == null){
            singleLoginDialog = new Dialog(getActivity(),R.style.Dialog_Translucent_Background);
            singleLoginDialog.setContentView(R.layout.dialog_single_login);
            singleLoginDialog.setCancelable(false);

            Button btnCancel = singleLoginDialog.findViewById(R.id.btn_cancel);
            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    singleLoginDialog.dismiss();
                    if(mFingerprintIdentify != null){
                        mFingerprintIdentify.cancelIdentify();
                    }
                }
            });

            codeView = singleLoginDialog.findViewById(R.id.verification_code_view);
            codeView.setOnCodeFinishListener(new VerificationCodeView.OnCodeFinishListener() {
                @Override
                public void onComplete(String content) {
                    if(StringTools.pswValide(content)) {
                        startActivity(LoginOrRegisterActivity.class);
                        onBackAction();
                        SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,false);
                    }else{
                        showToast("家长密码错误，请重新输入");
                    }
                }
            });
        }

        if(mFingerprintIdentify == null){
            mFingerprintIdentify = new FingerprintIdentify(BabyApplication.getInstance(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
                @Override
                public void onCatchException(Throwable exception) {
                    Log.e(TAG,exception.getLocalizedMessage());
                }
            });
        }

        TextView tvDes = singleLoginDialog.findViewById(R.id.tv_description);
        ImageView parentImg = singleLoginDialog.findViewById(R.id.parent_psw_img);
        ImageView fingerIconImg = singleLoginDialog.findViewById(R.id.parent_finger_icon_img);
        final TextView hintText = singleLoginDialog.findViewById(R.id.parent_dialog_hint_tv);
        hintText.setVisibility(View.GONE);
        if(mFingerprintIdentify.isFingerprintEnable()
                && mFingerprintIdentify.isHardwareEnable()
                && mFingerprintIdentify.isRegisteredFingerprint()){

            parentImg.setVisibility(View.GONE);
            fingerIconImg.setVisibility(View.VISIBLE);

            tvDes.setText("发现您的账号：" + SharedPreferencesUtils.getStringDate(
                    Constants.LOGIN_MOBILE_SHAREPREFERS_KEY) + " 已经在别的设备上登录，请验证指纹或者家长密码后重新登陆。");

            mFingerprintIdentify.startIdentify(5, new BaseFingerprint.FingerprintIdentifyListener() {
                @Override
                public void onSucceed() {
                    startActivity(LoginOrRegisterActivity.class);
                    onBackAction();
                    SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,false);
                    singleLoginDialog.dismiss();
                }

                @Override
                public void onNotMatch(int availableTimes) {
                    hintText.setVisibility(View.VISIBLE);
                    hintText.setText("指纹不匹配，还剩余" + availableTimes + "次机会");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);

                }

                @Override
                public void onFailed(boolean isDeviceLocked) {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);
                }

                @Override
                public void onStartFailedByDeviceLocked() {
                    hintText.setText("指纹尝试过多，请使用家长密码");
                    Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.shake);
                    hintText.startAnimation(shake);
                }
            });
        }else {
            parentImg.setVisibility(View.VISIBLE);
            fingerIconImg.setVisibility(View.GONE);
            tvDes.setText("发现您的账号：" + SharedPreferencesUtils.getStringDate(
                    Constants.LOGIN_MOBILE_SHAREPREFERS_KEY) + " 已经在别的设备上登录，请输入家长密码后重新登陆。");
        }

        if(codeView != null){
            codeView.clear();
        }

        if(!singleLoginDialog.isShowing() && !getActivity().isFinishing()){
            singleLoginDialog.show();
        }
    }

    /**
     * 显示加载动画
     *
     */
    protected void showWaitDialog() {

        if(mWaitDialog != null && !mWaitDialog.isShowing() && !getActivity().isFinishing()){
            mWaitDialog.show();
        }

    }

    /**
     * 关闭加载动画
     *
     */
    protected void dismissWaitDialog() {
        FragmentActivity fragmentActivity = getActivity();
        if (fragmentActivity == null || fragmentActivity.isFinishing()){
            return;
        }

        if(mWaitDialog != null && mWaitDialog.isShowing()){
            mWaitDialog.dismiss();
        }
    }

    public boolean isAllowBack() {
        return baseActivity.isAllowBack();
    }

    public void setAllowBack(boolean allowBack) {
        if(baseActivity != null){
            baseActivity.setAllowBack(allowBack);
        }
    }

}
